//
//  GlobalContext.m
//  LiMinProject
//
//  Created by FM123 on 2017/5/9.
//  Copyright © 2017年 LiMin. All rights reserved.
//

#import "GlobalContext.h"
//#import "StockData.h"
//#import "LoginInfo.h"
//#import "CustomAlertView.h"
//#import "DBHelper.h"
//#import "InfoModel.h"
//#import "UIImage+Helpers.h"
@implementation GlobalContext

static const CGFloat CSToastShadowOpacity       = 0.8;
static const CGFloat CSToastShadowRadius        = 6.0;
static const CGSize  CSToastShadowOffset        = { 4.0, 4.0 };
//+(BOOL)isLogin{
//
//    BOOL flag = false;
//
//    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    NSArray* facebookCookies = [cookies cookies];
//
//    for (NSHTTPCookie* cookie in facebookCookies) {
//        if([cookie.name isEqualToString:@"USER_ID"]){
//
//            InfoModel *_userInfoModel = [DBHelper getUserInfoFromDB];
//
//            if (_userInfoModel) {
//                flag = true;
//                [self setCookies:cookie.value];
//            }
//
//            break;
//        }
//    }
//
//    return flag;
//
//}
//+(NSString *)getUserId{
//
//    NSString *userId = @"";
//
//    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    NSArray* facebookCookies = [cookies cookies];
//
//    for (NSHTTPCookie* cookie in facebookCookies) {
//        if([cookie.name isEqualToString:@"USER_ID"]){
//            userId = cookie.value;
//            break;
//        }
//    }
//
//    return userId;
//
//}
//+(void)setCookies:(NSString *)userId{
//
//    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    //    NSArray* facebookCookies = [cookies cookiesForURL:
//    //                                [NSURL URLWithString:Domain]];
//    NSArray* facebookCookies = [cookies cookies];
//
//    for (NSHTTPCookie* cookie in facebookCookies) {
//        if([cookie.name isEqualToString:@"USER_ID"]){
//            [cookies deleteCookie:cookie];
//            break;
//        }
//    }
//
//    NSDictionary *properties1 = [[NSMutableDictionary alloc] init];
//    [properties1 setValue:userId forKey:NSHTTPCookieValue];       //乐居
//    [properties1 setValue:@"USER_ID" forKey:NSHTTPCookieName];
//    [properties1 setValue:Domain forKey:NSHTTPCookieDomain];
//    [properties1 setValue:[NSDate dateWithTimeIntervalSinceNow:24*60*60] forKey:NSHTTPCookieExpires];
//    [properties1 setValue:@"/" forKey:NSHTTPCookiePath];
//    NSHTTPCookie *cookie1 = [[NSHTTPCookie alloc] initWithProperties:properties1];
//    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie1];
//
//}
//+(NSString *)getId:(int)length{
//
//    NSString *idStr =@"";
//
//    for(int i=0;i<length;i++){
//
//        int value =arc4random_uniform(10);
//
//        idStr =[NSString stringWithFormat:@"%@%d",idStr,value];
//    }
//
//    return  idStr;
//}
//+(void)showAlertView:(NSString *)message {
//
//    WWLog(@"message %@",message);
//    CustomAlertView *alert=[[CustomAlertView alloc]initAlertWithTitle:@"温馨提示 !" andText:message andCancelButton:NO andStadu:1];
//    [alert setTitleFont:Font_Regular(18)];
//    [alert setTextFont:Font_Regular(14)];
//    [alert.defaultButton setTitle:@"我知道了" forState:UIControlStateNormal];
//
//    [alert show];
//
//
//}
//+(void)showAlertView:(NSString *)message andSure:(sureBlock)sureBlock{
//
//    CustomAlertView *alert=[[CustomAlertView alloc]initAlertWithTitle:@"温馨提示 !" andText:message andCancelButton:NO andStadu:1];
//    [alert setTitleFont:Font_Regular(18)];
//    [alert setTextFont:Font_Regular(14)];
//    alert.completionClickBlock = ^(CustomAlertView *alertObj, UIButton *button) {
//
//        if (button == alertObj.defaultButton) {
//            sureBlock();
//        }
//
//    };
//    [alert.defaultButton setTitle:@"我知道了" forState:UIControlStateNormal];
//
//    [alert show];
//
//
//}
//
//+(void)showAlertView:(NSString *)message yesOrNo:(BOOL)yesOrNo {
//    //yesOrNo:YES   显示确认返回按钮           NO：只有确定按钮
//    CustomAlertView *alert = [[CustomAlertView alloc]initAlertWithTitle:@"温馨提示 !" andText:message andCancelButton:YES andStadu:1];
//    [alert setTitleFont:[UIFont fontWithName:@"Verdana" size:25.0f]];
//    [alert.defaultButton setTitle:@"确定" forState:UIControlStateNormal];
//    [alert.cancelButton setTitle:@"返回" forState:UIControlStateNormal];
//    [alert.cancelButton addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
//    alert.cornerRadius = 3.0f;
//    [alert show];
//}
//+(void)showAlertViewWithTitle:(NSString*)title andText:(NSString *)message defaultButton:(NSString*)defaultStr cancelButton:(NSString*)cancelStr andSure:(sureBlock)sureBlock andFale:(faleBlock)faleBlock; {
//    //yesOrNo:YES   显示确认返回按钮           NO：只有确定按钮
//    NSString *string;
//    if (title.length>0) {
//        string=title;
//    }else{
//        string=@"温馨提示 !";
//    }
//
//    CustomAlertView *alert = [[CustomAlertView alloc]initAlertWithTitle:string andText:message andCancelButton:YES andStadu:1];
//    [alert setTitleFont:[UIFont fontWithName:@"Verdana" size:25.0f]];
//    [alert.defaultButton setTitle:cancelStr forState:UIControlStateNormal];
//    [alert.cancelButton setTitle:defaultStr forState:UIControlStateNormal];
//    [alert.cancelButton addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
//    alert.cornerRadius = 3.0f;
//    alert.completionClickBlock = ^(CustomAlertView *alertObj, UIButton *button) {
//        if(button == alertObj.defaultButton) {
//            faleBlock(nil);
//        } else {
//
//            sureBlock(nil);
//        }
//    };
//    [alert show];
//}
//+ (void)cancelClick {
//    WWLog(@"成功");
//}
//+(void)showAlertView:(NSString *)message andSure:(sureBlock)sureBlock andFale:(faleBlock)faleBlock;{
//
//    CustomAlertView *alert = [[CustomAlertView alloc]initAlertWithTitle:@"温馨提示 !" andText:message andCancelButton:YES andStadu:1];
//    [alert setTitleFont:[UIFont fontWithName:@"Verdana" size:25.0f]];
//    [alert.defaultButton setTitle:@"确定" forState:UIControlStateNormal];
//    [alert.cancelButton setTitle:@"返回" forState:UIControlStateNormal];
//    [alert.cancelButton addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
//    alert.cornerRadius = 3.0f;
//    alert.completionClickBlock = ^(CustomAlertView *alertObj, UIButton *button) {
//        if(button == alertObj.defaultButton) {
//            sureBlock(nil);
//        } else {
//            faleBlock(nil);
//        }
//    };
//    [alert show];
//}
//
//+(void)showTextToast:(NSString *)text view:(UIView *)view delay:(int)second{
//
//        __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//        hud.mode = MBProgressHUDModeText;
//        hud.color=Color_fac444;
//        hud.labelColor=[UIColor whiteColor];
//        hud.labelText = text;
//
//        [hud showAnimated:YES whileExecutingBlock:^{
//            sleep(second);
//        } completionBlock:^{
//            [MBProgressHUD hideHUDForView:view animated:YES];
//        }];
//
////    CGSize constraint1 = CGSizeMake(MAXFLOAT,21);
//////      CGSize size1 = [text  sizeWithFont:[UIFont fontWithName:@"STHeitiSC-Light" size:16.0f] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
//////
////
////    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:kPercenX_scale(10)]};
////    CGSize size1 = [text boundingRectWithSize:constraint1 options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
////
////    if (size1.width>=view.frame.size.width) {
////        size1.width = view.frame.size.width-60;
////    }
////    else
////        size1.width = size1.width+20;
////
////    LoginInfo *globalLoginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
////
////    if (!globalLoginInfo.toast) {
////        globalLoginInfo.toast = [[UILabel alloc] init];
////        [globalLoginInfo.toast setBackgroundColor:Color_fac444];//[[UIColor blackColor] colorWithAlphaComponent:0.7]
////        globalLoginInfo.toast.layer.cornerRadius = 10;
////        globalLoginInfo.toast.layer.shadowColor = [UIColor blackColor].CGColor;
////        globalLoginInfo.toast.layer.shadowOpacity = CSToastShadowOpacity;
////        globalLoginInfo.toast.layer.shadowRadius = CSToastShadowRadius;
////        globalLoginInfo.toast.layer.shadowOffset = CSToastShadowOffset;
////        globalLoginInfo.toast.textAlignment = NSTextAlignmentCenter;
////        [globalLoginInfo.toast setTextColor:[UIColor whiteColor]];
////        globalLoginInfo.toast.font = [UIFont fontWithName:@"STHeitiSC-Light" size:16.0f];
////        globalLoginInfo.toast.layer.masksToBounds = YES;
////    }
////
////    [globalLoginInfo.toast setText:text];
////    globalLoginInfo.toast.frame = CGRectMake(20, 0, view.frame.size.width-40,50);
////    globalLoginInfo.toast.center = view.center;
////    globalLoginInfo.toast.alpha = 0.8;
////    globalLoginInfo.toast.center = CGPointMake(view.center.x,-50);
////    [view addSubview:globalLoginInfo.toast];
////
////
////    POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionY];
////    positionAnimation.toValue = @(view.center.y);
////    positionAnimation.springBounciness = 10;
////    [positionAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
////
////        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0*NSEC_PER_SEC));
////        dispatch_after(time, dispatch_get_main_queue(), ^{
////
////            [self hideToast:nil];
////        });
////    }];
////
////    POPSpringAnimation *scaleAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerScaleXY];
////    scaleAnimation.springBounciness = 20;
////    scaleAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(1.2, 1.4)];
////
////    [globalLoginInfo.toast.layer pop_addAnimation:positionAnimation forKey:@"positionAnimation"];
////    [globalLoginInfo.toast.layer pop_addAnimation:scaleAnimation forKey:@"scaleAnimation"];
//
//}
//+(void)hideToast:(id)sender{
//
//    LoginInfo *globalLoginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
//
//    POPBasicAnimation *opacityAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerOpacity];
//    opacityAnimation.toValue = @(0.0);
//    [opacityAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
//        [globalLoginInfo.toast removeFromSuperview];
//    }];
//    [globalLoginInfo.toast.layer pop_addAnimation:opacityAnimation forKey:@"opacityAnimation"];
//
//}
//+(void)hide{
//
//    LoginInfo *globalLoginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
//
//    [UIView setAnimationsEnabled:true];
//    [UIView animateWithDuration:0.3f
//                          delay:0.0f
//                        options:UIViewAnimationOptionTransitionFlipFromLeft
//                     animations:^{
//
//
//                         globalLoginInfo.progressBarView.alpha = 0;
//
//                     }
//                     completion:^(BOOL finished) {
//
//                         [globalLoginInfo.progressBarView.activityIndicator stopAnimating];
//                         [globalLoginInfo.progressBarView removeFromSuperview];
//                     }
//     ];
//
//
//}
//+(void)makeBeginActivity{
////    LoginInfo *globalLoginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
////
////    CGRect rect = CGRectMake(0, 64,WIDTH , HEIGHT-64);
////    globalLoginInfo.activityView = [[ActivityView alloc] initWithFrame:rect];
////    [globalLoginInfo.activityView beginAnimation];
////    globalLoginInfo.activityView.backgroundColor=[UIColor redColor];
////    [[UIApplication sharedApplication].keyWindow addSubview:globalLoginInfo.activityView];
//
//}
//+(void)endActive{
//
//    LoginInfo *globalLoginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
//
//    [UIView setAnimationsEnabled:true];
//    [UIView animateWithDuration:0.3f
//                          delay:0.0f
//                        options:UIViewAnimationOptionTransitionFlipFromLeft
//                     animations:^{
//
//
//                         globalLoginInfo.activityView.alpha = 0;
//
//                     }
//                     completion:^(BOOL finished) {
//
////                         [globalLoginInfo.activityView endAnimating];
////                         [globalLoginInfo.activityView removeFromSuperview];
//                     }
//     ];
//
//}
//+(void)makeToastActivity:(UIView *)view{
//
//    LoginInfo *globalLoginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
////    if (!globalLoginInfo.progressBarView) {
//
//        //        CGRect rect = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
//        CGRect rect = CGRectMake(0, StatusBarAndNavBarHeight, view.frame.size.width, view.frame.size.height-StatusBarAndNavBarHeight);
//        globalLoginInfo.progressBarView = [[ProgressBarView alloc] initWithFrame:rect];
//
////    }
//    if(!globalLoginInfo.progressBarView.activityIndicator){
//
//        globalLoginInfo.progressBarView.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,80.0f,80.0f)];
//        //    [globalLoginInfo.progressBarView.activityIndicator setCenter:globalLoginInfo.progressBarView.progressView.center];
//        [globalLoginInfo.progressBarView.activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
//        [globalLoginInfo.progressBarView.progressView addSubview:globalLoginInfo.progressBarView.activityIndicator];
//
//        [globalLoginInfo.progressBarView.activityIndicator startAnimating];
//
//    }
//
//
//    globalLoginInfo.progressBarView.alpha = 0;
//    [globalLoginInfo.progressBarView.activityIndicator startAnimating];
//    globalLoginInfo.progressBarView.activityIndicator.color=OG_MAIN_REDCOLOR;
//    //     globalLoginInfo.progressBarView.activityIndicator.backgroundColor=
//    globalLoginInfo.progressBarView.center = view.center;
////    [view addSubview:globalLoginInfo.progressBarView];
//    globalLoginInfo.progressBarView.backgroundColor=[UIColor redColor];
//    globalLoginInfo.progressBarView.center = [UIApplication sharedApplication].keyWindow.center;
//    [[UIApplication sharedApplication].keyWindow addSubview:globalLoginInfo.progressBarView];
//    [UIView setAnimationsEnabled:true];
//    [UIView animateWithDuration:0.3f
//                          delay:0.0f
//                        options:UIViewAnimationOptionTransitionFlipFromLeft
//                     animations:^{
//
//
//                         globalLoginInfo.progressBarView.alpha = 1;
//
//                     }
//                     completion:^(BOOL finished) {
//
//                     }
//     ];
//
//
//
//}
//
//+(NSString *)toPinYin:(NSString *)name{
//    
//    ChineseString *chineseString=[[ChineseString alloc]init];
//    
//    chineseString.string=[NSString stringWithString:name];
//    
//    if(chineseString.string==nil){
//        chineseString.string=@"";
//    }
//    
//    if(![chineseString.string isEqualToString:@""]){
//        NSString *pinYinResult=[NSString string];
//        for(int j=0;j<chineseString.string.length;j++){
//            NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",pinyinFirstLetter([chineseString.string characterAtIndex:j])]uppercaseString];
//            
//            pinYinResult=[pinYinResult stringByAppendingString:singlePinyinLetter];
//        }
//        chineseString.pinYin=pinYinResult;
//    }else{
//        chineseString.pinYin=@"";
//    }
//    
//    return chineseString.pinYin;
//}

+(BOOL)validateMobile:(NSString *)mobileNum
{
    
    NSString * MOBILE = @"^1\\d{10}$";
    //    NSString *MOBILE = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(178))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
//判断手机号码格式是否正确
//+ (BOOL)validateMobile:(NSString *)mobileNum
//{
//    mobileNum = [mobileNum stringByReplacingOccurrencesOfString:@" " withString:@""];
//    if (mobileNum.length != 11)
//    {
//        return NO;
//    }else{
//        /**
//         * 移动号段正则表达式
//         */
//        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
//        /**
//         * 联通号段正则表达式
//         */
//        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
//        /**
//         * 电信号段正则表达式
//         */
//        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
//        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//        BOOL isMatch1 = [pred1 evaluateWithObject:mobileNum];
//        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
//        BOOL isMatch2 = [pred2 evaluateWithObject:mobileNum];
//        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
//        BOOL isMatch3 = [pred3 evaluateWithObject:mobileNum];
//
//        if (isMatch1 || isMatch2 || isMatch3) {
//            return YES;
//        }else{
//            return NO;
//        }
//    }
//}
+(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
    BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
}

#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)
+(BOOL)contains:(NSString *)str1 str2:(NSString *)str2{
    if (str1==nil  || str2==nil) {
        return false;
    }
    return [str1 rangeOfString: str2 ].location != NSNotFound;
}
+(CGRect)customFrame:(CGRect)frame x:(int)x y:(int)y width:(int)width height:(int)height{
    
    int x1= x;
    int y1= y;
    int width1= width;
    int height1= height;
    
    if (x1==0) {
        x1 = frame.origin.x;
    }
    if (y1==0) {
        y1 = frame.origin.y;
    }
    if (width1==0) {
        width1 = frame.size.width;
    }
    if (height1==0) {
        height1 = frame.size.height;
    }
    
    CGRect rect = CGRectMake(x1, y1, width1, height1);
    
    return rect;
}


//
//+(void)updateLocationMethod {
//    WWLog(@"updateLocation");
//
//    LoginInfo  *loginInfo =[[StockData getSingleton] valueForKey:@"loginInfo"];
//    if(loginInfo.locationTracker)
//        [loginInfo.locationTracker updateLocationToServer];
//}
+(void)isAllowdOpenCameraSure:(sureBlock)sureBlock andFale:(faleBlock)faleBlock;{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        // 应用第一次申请权限调用这里
        if ([Helper isCameraNotDetermined])
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (granted)
                    {
                        // 用户授权
                       sureBlock();
                    }
                    else
                    {
                        // 用户拒绝授权
                         faleBlock(@"拒绝访问摄像头，可去设置隐私里开启");
//                        [GlobalContext showAlertView:@"拒绝访问摄像头，可去设置隐私里开启" andSure:^{
//
//                            return ;
//                        }];
                      
                    }
                });
            }];
        }
        // 用户已经拒绝访问摄像头
        else if ([Helper isCameraDenied])
        {
             faleBlock(@"拒绝访问摄像头，可去设置隐私里开启");
//            [GlobalContext showAlertView:@"拒绝访问摄像头，可去设置隐私里开启" andSure:^{
//
//                return ;
//            }];
          
        }
        
        // 用户允许访问摄像头
        else
        {
            sureBlock();
        }
    }
    else
    {
        // 当前设备不支持摄像头，比如模拟器
        faleBlock(@"当前设备不支持拍照");
//        [GlobalContext showAlertView:@"当前设备不支持拍照" andSure:^{
//
//            return ;
//        }];
    }
    
    
}
+(void)isAllowdGetPhotoSure:(sureBlock)sureBlock andFale:(faleBlock)faleBlock;{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        // 第一次安装App，还未确定权限，调用这里
        if ([Helper isPhotoAlbumNotDetermined])
        {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
            {
                // 该API从iOS8.0开始支持
                // 系统弹出授权对话框
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied)
                        {
                            // 用户拒绝，跳转到自定义提示页面
                             faleBlock(@"拒绝访问相册，可去设置隐私里开启");
                        }
                        else if (status == PHAuthorizationStatusAuthorized)
                        {
                            // 用户授权，弹出相册对话框
                            sureBlock();
                        }
                    });
                }];
            }
            else
            {
                // 以上requestAuthorization接口只支持8.0以上，如果App支持7.0及以下，就只能调用这里。
                sureBlock();
                
            }
        }
        else if ([Helper isPhotoAlbumDenied])
        {
            // 如果已经拒绝，则弹出对话框
            faleBlock(@"拒绝访问相册，可去设置隐私里开启");
//            [GlobalContext showAlertView:@"拒绝访问相册，可去设置隐私里开启" andSure:^{
//
//                return ;
//            }];
        }
        else
        {
            // 已经授权，跳转到相册页面
            sureBlock();
        }
    }
    else
    {
        // 当前设备不支持打开相册
        // 当前设备不支持摄像头，比如模拟器
        faleBlock(@"当前设备不支持拍照");
//        [GlobalContext showAlertView:@"当前设备不支持拍照" andSure:^{
//            
//            return ;
//        }];
    }
}
+(void)popBackToViewControllerWithController:(UIViewController *)controller andIndex:(int)index;{
    
    NSArray * ctrlArray = controller.navigationController.viewControllers;
    [controller.navigationController popToViewController:[ctrlArray objectAtIndex:index] animated:YES];
}

// 根据图片url获取图片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
//  获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取gif图片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取jpg图片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}
@end
